import React, { Component } from 'react'
import { Button, Card, Col, DatePicker, Form, Icon, Input, message, Modal, Row, Spin, Table, Tabs, Tooltip } from 'antd'
import moment from 'moment'
import { fetchPost } from '../../../utils/request'
import FundAction from './FundAction'

const FormItem = Form.Item
const TabPane = Tabs.TabPane
const RangePicker = DatePicker.RangePicker
class Index extends Component {
  constructor (props) {
    super(props)
    this.state = {
      modalVisible: false,
      modalTitle: '',
      searchParams: {
        startTime: moment().subtract(8, 'day').format('YYYY-MM-DD'),
        endTime: moment().subtract(1, 'day').format('YYYY-MM-DD'),
        accountType: '0'
      },
      page: {
        currentPage: 1,
        pageSize: 10
      },
      data: {},
      tableLoading: false,
      cashType: null
    }
  }
  componentDidMount () {
    this.getData()
  }
  // 重置
  resetSearchParams () {
    this.props.form.resetFields()
    this.setState({
      searchParams: {
        ...this.state.searchParams,
        startTime: moment().subtract(8, 'day').format('YYYY-MM-DD'),
        endTime: moment().subtract(1, 'day').format('YYYY-MM-DD')
      },
      page: {
        currentPage: 1,
        pageSize: 10
      }
    }, () => this.getData())
  }
  // 搜索
  search (e) {
    // 阻止页面刷新
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 去除空值
        for (var key in values) {
          if (!values[key]) {
            delete values[key]
          }
        }
        // 格式转换
        if (values.queryDate) {
          let startTime = values.queryDate[0].format('YYYY-MM-DD')
          let endTime = values.queryDate[1].format('YYYY-MM-DD')
          this.setState({
            page: {
              currentPage: 1,
              pageSize: 10
            },
            searchParams: {
              ...this.state.searchParams,
              startTime,
              endTime
            }
          }, () => this.getData()
          )
        }
      }
    })
  }
  // 获取表格数据
  getData () {
    this.setState({
      tableLoading: true
    })
    const url = `/account/accountOrderList?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`
    fetchPost(url, this.state.searchParams).then((res) => {
      this.setState({
        tableLoading: false
      })
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            data: res.data,
            page: res.data.page ? res.data.page : this.state.page
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }
  // 下一页
  nextPage (currentPage) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage
      }
    }, () => {
      this.getData()
    })
  }
  // 禁用之后时间
  static disabledDate (current) {
    return current.valueOf() > Date.now()
  }
  // 标签切换
  tabOnChange (key) {
    this.setState({
      searchParams: {
        ...this.state.searchParams,
        accountType: key
      },
      data: {},
      page: {
        currentPage: 1,
        pageSize: 10
      }
    }, () => this.getData())
  }
  // 显示资金操作弹框
  openFundActionModal (type, modalTitle) {
    this.setState({
      modalVisible: true,
      modalTitle: modalTitle,
      cashType: type
    })
  }
  // 取消弹框
  modalCancel () {
    this.Fundaction.props.form.resetFields()
    this.setState({
      modalVisible: false
    })
  }
  handleOk () {
    let pass = this.Fundaction.doFundAction()
    if (pass) {
      this.setState({
        modalVisible: false
      }, () => setTimeout(() => this.getData(), 2000))
    }
  }
  // 拿到子组件的 this指向
  bindRef (ref) {
    this.Fundaction = ref
  }
  render () {
    let self = this
    const columns = [{
      title: '序号',
      dataIndex: 'no'
    }, {
      title: '时间',
      dataIndex: 'tradingTime'
    }, {
      title: '业务类型',
      dataIndex: 'businessType'
    }, {
      title: '账户',
      dataIndex: 'intoAccountNo'
    }, {
      title: '金额',
      dataIndex: 'balance'
    }, {
      title: '订单号',
      dataIndex: 'tradeNo'
    }, {
      title: '三方流水号',
      dataIndex: 'threeSerialNo'
    }
    ]

    const { getFieldDecorator } = this.props.form
    const pagination = {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: false,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.nextPage(current)
      }
    }
    return (
      <div>
        <Card bordered={false} noHovering>
          <Form layout='inline' onSubmit={(e) => this.search(e)}>
            <FormItem label={(<span>
              起止时间&nbsp;
              <Tooltip title='若查询当日订单，请保持起止时间一致'>
                <Icon type='question-circle-o' />
              </Tooltip>
            </span>)}>
              {getFieldDecorator('queryDate', {
                initialValue: [moment().subtract(8, 'day'), moment().subtract(1, 'day')],
                rules: [
                  {
                    required: true,
                    message: '请选择起止时间'
                  }
                ]
              }
              )(<RangePicker disabledDate={Index.disabledDate} />)}
            </FormItem>

            <FormItem>
              <Button type='primary' htmlType='submit'>搜索</Button>
              <Button style={{marginLeft: 6}} onClick={() => this.resetSearchParams()}><Icon type='reload' /></Button>
            </FormItem>
          </Form>
        </Card>
        <Spin spinning={this.state.tableLoading} delay={200}>
          <Tabs defaultActiveKey='0' onChange={(e) => this.tabOnChange(e)} type='card'>
            <TabPane tab='捷融资金账户' key='0'>
              <Form layout='inline' >
                <FormItem>
                  <Input addonBefore='电子账户' value={this.state.data.accountNo} />
                </FormItem>
                <FormItem>
                  <Input addonBefore='余额' value={this.state.data.accountBalance} addonAfter='元' />
                </FormItem>
              </Form>
            </TabPane>
            <TabPane tab='中智赢资金账户' key='1' >
              <Form layout='inline' >
                <FormItem>
                  <Input addonBefore='电子账户' value={this.state.data.accountNo} />
                </FormItem>
                <FormItem>
                  <Input addonBefore='余额' value={this.state.data.accountBalance} addonAfter='元' />
                </FormItem>
                <FormItem>
                  <Button type='primary' onClick={() => this.openFundActionModal('zzj-jr', '转账')}>转账</Button>
                </FormItem>
                <FormItem>
                  <Button style={{marginLeft: 6}} type='primary' onClick={() => this.openFundActionModal('withdrawa-zzy', '提现')}>提现</Button>
                </FormItem>
              </Form>
              <Table style={{marginTop: 30}} columns={columns} dataSource={this.state.data.cashAccountInfos} bordered pagination={pagination} rowKey='no' />
            </TabPane>
            <TabPane tab='鹿城资金账户' key='2'>
              <Form layout='inline' >
                <FormItem>
                  <Input addonBefore='电子账户' value={this.state.data.accountNo} />
                </FormItem>
                <FormItem>
                  <Input addonBefore='余额' value={this.state.data.accountBalance} addonAfter='元' />
                </FormItem>
                <FormItem>
                  <Button type='primary' onClick={() => this.openFundActionModal('withdrawa-lc', '提现')}>提现</Button>
                </FormItem>
              </Form>
              <Table style={{marginTop: 30}} columns={columns} dataSource={this.state.data.cashAccountInfos} bordered pagination={pagination} rowKey='no' />
            </TabPane>
          </Tabs>
        </Spin>
        <Modal title={this.state.modalTitle} visible={this.state.modalVisible} onOk={() => this.handleOk()} onCancel={() => this.modalCancel()}>
          <FundAction triggerRef={(e) => this.bindRef(e)} action={this.state.modalTitle} cashType={this.state.cashType} balance={this.state.data.accountBalance} />
        </Modal>
      </div>
    )
  }
}

export default Form.create()(Index)
